<?php

namespace app\api\controller\order;

use app\api\BaseController;
use app\api\service\CommissionService;
use think\facade\Db;
use think\facade\Queue;
use WeChat\Contracts\Tools;

class TradeController extends BaseController
{
    //加销量，送积分，产品分润，加消费记录
    /**
     * 微信回调
     * */

    public function wxNotify()
    {
        $result = Tools::xml2arr(file_get_contents('php://input'));
        if (!empty($result)) {
            if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS') {
                $this->changeTrade($result['out_trade_no'], $result['time_end']);

                echo '<xml>' .
                    '<return_code><![CDATA[SUCCESS]]></return_code>' .
                    '<return_msg><![CDATA[OK]]></return_msg>' .
                    '</xml>';
                exit();
            }
        }

    }

    /**
     * 支付宝回调
     * */
    public function aliNotify()
    {
        $post = $_POST;
        if (!empty($post)) {
            if ($post['trade_status'] == 'TRADE_SUCCESS') {
                $this->changeTrade($post['out_trade_no'], $post['gmt_payment']);
                echo 'success';
            }
        }
    }

    public function changeTrade($out_trade_no, $time_end)
    {
        $tradeOrder = Db::name('order_trade')->where('trade_status', '<>', 1)->where('out_trade_no', $out_trade_no)->find();
        if (!empty($tradeOrder)) {
            $order_id = $tradeOrder['order_id'];
            $order = Db::name('order')->where('id', $order_id)->where('status', 1)->where('store_id', $tradeOrder['store_id'])->find();
            if (!empty($order)) {

                //更新支付订单信息
                Db::name('order_trade')->where('out_trade_no', $out_trade_no)
                    ->update([
                        'trade_status' => 1,
                        'trade_time' => strtotime($time_end),
                    ]);

                //修改订单状态
                if ($order['logistics_mode'] == 2) {
                    Db::name('order')->where('id', $order_id)->update(['status' => 3, 'ship_time' => time()]);
                } else {
                    Db::name('order')->where('id', $order_id)->update(['status' => 2]);
                }

                //积分订单
                if ($order['order_type'] == 3) {
                    Queue::push('app\store\job\Account@integral', [
                        'user_id' => $order['user_id'],
                        'desc' => '积分兑换商品',
                        'change_type' => 2,
                        'integral' => $order['give_integral'],
                    ], 'userAccount');
                }

                //商城订单赠送积分
                if ($order['order_type'] == 1) {
                    if ($order['give_integral'] > 0) {
                        Queue::push('app\store\job\Account@integral', [
                            'user_id' => $order['user_id'],
                            'desc' => '购买商品',
                            'change_type' => 1,
                            'integral' => $order['give_integral'],
                        ], 'userAccount');
                    }
                    Db::name('finance')->insert(['uid' => $order['user_id'], 'money' => $order['real_amount'], 'f_type' => 1,
                        'status' => 1, 'desc' => '商城订单支付', 'source' => $order['id'], 'create_time' => time(),
                    ]);
                    //添加销量
                    $this->addSale($order_id);
                    //产品分润
                    $commisson = new CommissionService();
                    $commisson->productFr($order_id);
                }

                //套餐订单
                if ($order['order_type'] == 5) { //购买套餐

                    Db::name('finance')->insert(['uid' => $order['user_id'], 'money' => $order['real_amount'], 'f_type' => 1,
                        'status' => 3, 'desc' => '购买套餐', 'source' => $order['id'], 'create_time' => time(),
                    ]);

                    $combo = $this->findComboDetail($order['order_id']);
                    if ($combo['user_grade_id'] > 0) {
                        Db::name('user')->where('user_id', $order['user_id'])->update(['user_grade_id' => $combo['user_grade_id']]);
                    }

                    //设置赠送24张优惠劵
                    if ($combo['give_self_coupon_count'] > 0 && $combo['give_self_month_num'] > 0) {
                        $combo_price = $combo['sell_price']; //套餐金额
                        $give_self_coupon_count = $combo['give_self_coupon_count']; //赠送多少张卷
                        $give_self_month_num = $combo['give_self_month_num']; //每个月增送的数量
                        $give_total_price = bcdiv($combo_price, $give_self_coupon_count, 2); //每次的金额
                        if ($give_total_price > 0) {
                            $average_price = bcdiv($give_total_price, $give_self_month_num, 2); //每张的金额
                            if ($average_price > 0) {
                                Db::name('return_volume')->insert(['uid' => $order['user_id'], 'total' => $combo_price, 'count' => $give_self_coupon_count,
                                    'sy_count' => $give_self_coupon_count, 'month_count' => $give_self_month_num, 'amount' => $average_price, 'create_time' => time(),
                                ]);
                            }
                        }
                    }

                    if ($combo['give_integral'] > 0) {
                        Queue::push('app\store\job\Account@integral', [
                            'user_id' => $order['user_id'],
                            'desc' => '购买套餐',
                            'change_type' => 1,
                            'integral' => $combo['give_integral'],
                        ], 'userAccount');
                    }

                    if ($combo['give_balance'] > 0) {
                        Queue::push('app\store\job\Account@balance', [
                            'user_id' => $order['user_id'],
                            'desc' => '购买套餐',
                            'change_type' => 1,
                            'balance' => $combo['give_balance'],
                        ], 'userAccount');
                    }

                    if (!empty($combo['give_coupon'])) {
                        foreach ($combo['give_coupon'] as $v) {
                            Queue::push('app\store\job\Coupon', [
                                'user_id' => $order['user_id'],
                                'coupon_id' => $v['coupon_id'],
                                'num' => $v['give_num'],
                            ], 'userCoupon');
                        }
                    }

                }
            }
        }

    }

    /**
     * 添加销量
     */
    public function addSale($oid)
    {
        $order = Db::name('order_item')->where('order_id', $oid)->select();
        foreach($order as $k => $v) {
            Db::name('goods')->where('id', $v['goods_id'])->inc('total_sale', $v['buy_num'])->update();
        }
    }

    public function findComboDetail($order_id)
    {
        $combo = Db::name('combo')
            ->alias('a')
            ->field('a.user_grade_id,a.give_integral,a.give_coupon,a.give_balance')
            ->join('order_item b', 'a.id=b.goods_id')
            ->withAttr('give_coupon', function ($value) {
                if (empty($value)) {
                    return [];
                }
                return json_decode($value, true);
            })->where('b.order_id', $order_id)
            ->find();

        return $combo;
    }
}
